/*
 * @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
 */
package com.wugui.datatx.core.util;

import java.util.Stack;

import org.slf4j.Logger;

import lombok.extern.slf4j.Slf4j;

/**
 * 用于计时
 * 
 * @author jiangmy
 * @date 2018年1月15日 下午4:58:02
 * @since 1.0.0
 */
@Slf4j
public class TimeStackUtils {

	private static ThreadLocal<Stack<Long>> times = ThreadLocal.withInitial(() -> new Stack<>());

	public static void begin() {
		Stack<Long> stack = times.get();
		if (stack.size() > 30) {
			// 检测是否有遗漏
			log.warn("栈大小超过30,请检查是否有地方只begin()没有end()!!!");
			for (int i = 0; i < 10; i++) {
				stack.remove(0);
			}
		}
		stack.push(System.currentTimeMillis());
	}

	public static long end() {
		Stack<Long> stack = times.get();
		if (stack.isEmpty()) {
			log.warn("没有begin()操作,计时失败!!!");
			stack.push(System.currentTimeMillis());
			return 0;
		}
		long begin = stack.pop();
		if (stack.size() == 0) {
			stack.push(System.currentTimeMillis());
		}
		long time = System.currentTimeMillis() - begin;
		return time;
	}

	public static void clear() {
		Stack<Long> stack = times.get();
		if (!stack.isEmpty()) {
			stack.clear();
		}
	}

	/**
	 * 打印执行时间日志
	 * 
	 * @param warnMilllis
	 * @param message
	 * @param params
	 * @author jiangmy
	 * @date 2010-07-22 下午5:50:31
	 */
	public static void endAndLog(long warnMilllis, String message, Object... params) {
		endAndLog(log, warnMilllis, message, params);
	}

	/**
	 * 打印执行时间日志
	 * 
	 * @param log
	 * @param warnMilllis
	 * @param message
	 * @param params
	 * @author jiangmy
	 * @date 2010-07-22 下午5:50:31
	 */
	public static void endAndLog(Logger log, long warnMilllis, String message, Object... params) {
		long time = end();
		if (time >= warnMilllis) {
			log.warn(message + "【耗时:" + time + "ms】", params);
		} else {
			log.info(message + " 【耗时:" + time + "ms】", params);
		}
	}

	public static void endAndInfo(Logger log, long infoMilllis, String message, Object... params) {
		long time = end();
		if (time >= infoMilllis) {
			log.info(message + "【耗时:" + time + "ms】", params);
		} else {
			log.debug(message + " 【耗时:" + time + "ms】", params);
		}
	}

	/**
	 * sleep等待,单位毫秒.
	 * 
	 * @param millis 毫秒
	 */
	public static void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {// NOSONAR
		}
	}

	public static void main(String[] args) {
		begin();
		sleep(30);
		begin();
		sleep(30);
		endAndLog(100, "测试计时:{}", "哈哈");
		sleep(300);
		endAndLog(100, "测试计时");

	}

	private TimeStackUtils() {
	}

}
